<template>
  <div class="admin-permission-management-container">
    <!-- 筛选区和设置图标同一行 -->
    <div class="filter-bar">
      <div class="filter-container">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          size="small"
        >
        </el-date-picker>

        <el-input
          v-model="searchQuery"
          placeholder="搜索账号"
          prefix-icon="el-icon-search"
          clearable
          @clear="handleSearch"
          @keyup.enter.native="handleSearch"
          style="width: 250px; margin-left: 10px;"
          size="small"
        >
        </el-input>

        <el-button type="primary" size="small" style="margin-left: 10px;" @click="handleSearch">查询</el-button>
        <el-button size="small" @click="resetSearch">重置</el-button>
        <el-button type="primary" size="small" style="margin-left: 10px;" @click="handleAdd">添加</el-button>
      </div>
      <div class="filter-setting-icon">
        <el-popover
          placement="bottom-end"
          width="220"
          trigger="click"
          v-model="showColumnSetting"
        >
          <div v-for="col in columns" :key="col.key">
            <el-checkbox v-model="col.visible">{{ col.label }}</el-checkbox>
          </div>
          <div style="text-align: right;">
            <el-button type="text" size="mini" @click="resetColumns">重置</el-button>
          </div>
          <i
            class="el-icon-setting"
            slot="reference"
            style="cursor: pointer; font-size: 20px; margin-left: 10px;"
          ></i>
        </el-popover>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-wrapper">
      <el-table
        :data="tableData"
        style="width: 100%;"
        border
        v-loading="loading"
      >
      <el-table-column v-if="getColumnVisible('index')"
        type="index"
        label="序号"
        width="80" align="center">
      </el-table-column>
      <el-table-column v-if="getColumnVisible('adminName')"
        prop="adminName"
        label="姓名"
        width="120">
      </el-table-column>
      <el-table-column v-if="getColumnVisible('phone')"
        prop="phone"
        label="账号"
        width="150">
      </el-table-column>
       <el-table-column v-if="getColumnVisible('role_name')"
        prop="role_name"
        label="角色组"
        min-width="150">
      </el-table-column>
       <el-table-column v-if="getColumnVisible('create_time')"
        prop="create_time"
        label="创建时间"
        width="180">
      </el-table-column>
       <el-table-column v-if="getColumnVisible('update_time')"
        prop="update_time"
        label="更新时间"
        width="180">
      </el-table-column>
      <el-table-column v-if="getColumnVisible('status')"
        prop="status"
        label="状态"
        width="100"
        align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column v-if="getColumnVisible('operate')"
        label="操作"
        width="330" align="center">
        <template slot-scope="scope">
           <el-switch
            v-model="scope.row.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-text="启用"
            inactive-text="禁用"
            :active-value="1"
            :inactive-value="0"
            size="small"
            @change="handleStatusChange(scope.row)"
          >
          </el-switch>
          <!-- <el-button type="text" size="small" style="margin-left: 10px; color: #409EFF;" @click="handleCharge(scope.row)">充值</el-button> -->
          <el-button type="text" size="small" style="margin-left: 10px;" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" size="small" style="margin-left: 10px; color: #F56C6C;" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件 -->
     <div class="pagination-container" style="margin-top: 20px; text-align: right;">
       <PageCom :total="total" :pageSize="pageSize" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange" :currentPage="currentPage"></PageCom>
    </div>

    <!-- 添加管理员弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="resetForm"
    >
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="姓名" prop="adminName">
          <el-input v-model="form.adminName" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" :disabled="isEdit"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="outpassword">
          <el-input v-model="form.outpassword" type="password" placeholder="请再次输入密码"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role_id">
          <el-select v-model="form.role_id" placeholder="请选择角色" style="width: 100%">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.role_name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
    
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 充值弹窗 -->
    <el-dialog
      title="充值"
      :visible.sync="chargeDialogVisible"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="resetChargeForm"
    >
      <el-form :model="chargeForm" :rules="chargeRules" ref="chargeForm" label-width="100px">
        <el-form-item label="管理员账号">
          <el-input v-model="chargeForm.phone" disabled></el-input>
        </el-form-item>
        <el-form-item label="当前余额">
          <el-input v-model="chargeForm.account" disabled>
            <template slot="prepend">¥</template>
          </el-input>
        </el-form-item>
        <el-form-item label="充值金额" prop="amount">
          <el-input v-model="chargeForm.amount" placeholder="请输入充值金额" type="number">
            <template slot="prepend">¥</template>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleChargeCancel">取 消</el-button>
        <el-button type="primary" @click="submitChargeForm" :loading="chargeLoading">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import PageCom from '@/components/PageCom.vue';
import { adminList, updateAdminStatus, deleteAdmin, groupList, addAdmin, editAdmin, adminCharge } from '@/api/contract';

export default {
  name: 'AdminPermissionManagementView',
  components: {
    PageCom,
  },
  data() {
    // 验证密码是否一致
    const validatePass = (rule, value, callback) => {
      if (!this.form.password) {
        callback();
        return;
      }
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      dateRange: null,
      searchQuery: '',
      tableData: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      loading: false,
      // 弹窗相关数据
      dialogVisible: false,
      submitLoading: false,
      roleList: [], // 角色列表
      dialogTitle: '添加管理员',
      isEdit: false,
      form: {
        id: '',
        adminName: '',
        phone: '',
        password: '',
        outpassword: '',
        role_id: '',
      },
      rules: {
        adminName: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        password: [
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        outpassword: [
          { validator: validatePass, trigger: 'blur' }
        ],
        role_id: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ]
      },
      // 字段显示控制配置
      columns: [
        { key: 'index', label: '序号', visible: true },
        { key: 'adminName', label: '姓名', visible: true },
        { key: 'phone', label: '账号', visible: true },
        { key: 'merchantNo', label: '商户号', visible: true },
        { key: 'account', label: '账号余额', visible: true },
        { key: 'role_name', label: '角色组', visible: true },
        { key: 'create_time', label: '创建时间', visible: true },
        { key: 'update_time', label: '修改时间', visible: true },
        { key: 'status', label: '状态', visible: true },
        { key: 'operate', label: '操作', visible: true }
      ],
      showColumnSetting: false,
      // 充值相关数据
      chargeDialogVisible: false,
      chargeLoading: false,
      chargeForm: {
        id: '',
        phone: '',
        account: '',
        amount: ''
      },
      chargeRules: {
        amount: [
          { required: true, message: '请输入充值金额', trigger: 'blur' },
          { pattern: /^-?[0-9]+(\.[0-9]{1,2})?$/, message: '请输入正确的金额格式', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.fetchAdminList();
    this.fetchRoleList();
  },
  methods: {
    // 获取管理员列表数据
    async fetchAdminList() {
      this.loading = true;
      try {
        const params = {
          page: this.currentPage,
          pageSize: this.pageSize,
          time: this.dateRange || [],
          keyword: this.searchQuery || '',
        };
        const response = await adminList(params);
        // console.log('Admin List API Response:', response);
        if (response.data.code === 200) {
          this.tableData = response.data.data.data || [];
          this.total = response.data.data.total || 0;

          if (this.tableData.length === 0 && this.total > 0) {
            // 如果当前页没有数据但总数大于0，尝试回到上一页或第一页
             if (this.currentPage > 1) {
                 this.currentPage--;
                 this.fetchAdminList(); // 重新获取数据
             } else {
                 this.$message.warning('当前筛选条件下暂无数据');
             }
          } else if(this.tableData.length === 0 && this.total === 0){
               this.$message.warning('暂无数据');
          }

        } else {
          this.$message.error(response.data.message || '获取数据失败');
          this.tableData = [];
          this.total = 0;
        }
      } catch (error) {
        console.error('获取管理员列表失败:', error);
        this.$message.error('获取数据失败，请稍后重试');
        this.tableData = [];
        this.total = 0;
      } finally {
        this.loading = false;
      }
    },
    // 每页条数改变
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1; // 切换每页条数时，重置到第一页
      this.fetchAdminList();
    },
    // 页码改变
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchAdminList();
    },
     handleSearch() {
      this.currentPage = 1; // 查询时重置到第一页
      this.fetchAdminList();
    },
    resetSearch() {
      this.dateRange = null;
      this.searchQuery = '';
      this.currentPage = 1;
      this.pageSize = 10; // 重置每页条数到默认值
      this.fetchAdminList();
    },
    handleExport() {
      // console.log('Export button clicked');
      // Implement export logic here
    },
    handleStatusChange(row) {
      this.$confirm(`确认要${row.status === 1 ? '启用' : '禁用'}该管理员账号吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await updateAdminStatus(row.id);
          if (response.data.code === 200) {
            this.$message.success('状态修改成功');
            // 刷新列表
            this.fetchAdminList();
          } else {
            this.$message.error(response.data.message || '状态修改失败');
            // 恢复开关状态
            row.status = row.status === 1 ? 0 : 1;
          }
        } catch (error) {
          console.error('状态修改失败:', error);
          this.$message.error('状态修改失败，请稍后重试');
          // 恢复开关状态
          row.status = row.status === 1 ? 0 : 1;
        }
      }).catch(() => {
        // 取消操作，恢复开关状态
        row.status = row.status === 1 ? 0 : 1;
        this.$message.info('已取消操作');
      });
    },
    handleEdit(row) {
      this.isEdit = true;
      this.dialogTitle = '编辑管理员';
      this.form = {
        id: row.id,
        adminName: row.adminName || '',
        phone: row.phone,
        password: '',
        outpassword: '',
        role_id: row.role_id,
      };
      this.dialogVisible = true;
      // 清除密码验证
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate(['password', 'outpassword']);
        }
      });
    },
    handleAdd() {
      this.isEdit = false;
      this.dialogTitle = '添加管理员';
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.resetForm();
      });
    },
    handleDelete(row) {
      this.$confirm('确认要删除该管理员账号吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await deleteAdmin(row.id);
          if (response.data.code === 200) {
            this.$message.success('删除成功');
            // 刷新列表
            this.fetchAdminList();
          } else {
            this.$message.error(response.data.message || '删除失败');
          }
        } catch (error) {
          console.error('删除失败:', error);
          this.$message.error('删除失败，请稍后重试');
        }
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    // 获取角色列表
    async fetchRoleList() {
      try {
        const response = await groupList();
        if (response.data.code === 200) {
          this.roleList = response.data.data || [];
        } else {
          this.$message.error(response.data.message || '获取角色列表失败');
        }
      } catch (error) {
        console.error('获取角色列表失败:', error);
        this.$message.error('获取角色列表失败，请稍后重试');
      }
    },
    handleCancel() {
      this.dialogVisible = false;
      this.resetForm();
    },
    resetForm() {
      this.form = {
        id: '',
        adminName: '',
        phone: '',
        password: '',
        outpassword: '',
        role_id: '',
      };
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
    },
    submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.submitLoading = true;
          try {
            // 如果是编辑状态且没有输入密码，则删除密码相关字段
            const submitData = { ...this.form };
            if (this.isEdit && !submitData.password) {
              delete submitData.password;
              delete submitData.outpassword;
            }
            
            const response = this.isEdit ? 
              await editAdmin(submitData) : 
              await addAdmin(submitData);
            
            if (response.data.code === 200) {
              this.$message.success(this.isEdit ? '更新成功' : '添加成功');
              this.dialogVisible = false;
              this.fetchAdminList();
            } else {
              this.$message.error(response.data.message || (this.isEdit ? '编辑失败' : '添加失败'));
            }
          } catch (error) {
            console.error('提交失败:', error);
            this.$message.error('操作失败，请稍后重试');
          } finally {
            this.submitLoading = false;
          }
        }
      });
    },
    getColumnVisible(key) {
      const col = this.columns.find(c => c.key === key);
      return col ? col.visible : false;
    },
    resetColumns() {
      this.columns.forEach(col => col.visible = true);
    },
    // 充值相关方法
    handleCharge(row) {
      this.chargeForm = {
        id: row.id,
        phone: row.phone,
        account: row.account || 0,
        amount: ''
      };
      this.chargeDialogVisible = true;
      this.$nextTick(() => {
        if (this.$refs.chargeForm) {
          this.$refs.chargeForm.clearValidate();
        }
      });
    },
    handleChargeCancel() {
      this.chargeDialogVisible = false;
      this.resetChargeForm();
    },
    resetChargeForm() {
      this.chargeForm = {
        id: '',
        phone: '',
        account: '',
        amount: ''
      };
      if (this.$refs.chargeForm) {
        this.$refs.chargeForm.resetFields();
      }
    },
    async submitChargeForm() {
      this.$refs.chargeForm.validate(async (valid) => {
        if (valid) {
          this.chargeLoading = true;
          try {
            const response = await adminCharge({
              id: this.chargeForm.id,
              amount: this.chargeForm.amount
            });
            
            if (response.data.code === 200) {
              this.$message.success(response.data.msg || '充值成功');
              this.chargeDialogVisible = false;
              this.fetchAdminList(); // 刷新列表
            } else {
              this.$message.error(response.data.msg || '充值失败');
            }
          } catch (error) {
            console.error('充值失败:', error);
            this.$message.error('充值失败，请稍后重试');
          } finally {
            this.chargeLoading = false;
          }
        }
      });
    }
  }
};
</script>

<style scoped>
.admin-permission-management-container {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 60px - 20px);
  box-sizing: border-box;
}

.filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-container {
  display: flex;
  align-items: center;
}

.filter-setting-icon {
  display: flex;
  align-items: center;
  height: 32px;
}

.table-wrapper {
  margin-top: 20px;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
}

.pagination-info-total {
  margin-top: 20px;
  text-align: right;
  color: #606266;
  font-size: 14px;
}

/* 表格样式 */
::v-deep .el-table {
  border: 1px solid #EBEEF5;
}

::v-deep .el-table th {
  background-color: #f5f7fa !important;
  color: #606266;
}

::v-deep .el-table td,
::v-deep .el-table th {
  border-bottom: 1px solid #EBEEF5;
  border-right: 1px solid #EBEEF5;
}

::v-deep .el-table th:last-child,
::v-deep .el-table td:last-child {
  border-right: none;
}

::v-deep .el-table::after,
::v-deep .el-table::before {
  background-color: transparent;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}

::v-deep .el-input__inner {
  background-color: white !important;
}

@media (max-width: 768px) {
  .admin-permission-management-container {
    padding: 15px 10px;
  }

  .filter-bar {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .filter-container {
    width: 100%;
    flex-wrap: wrap;
    gap: 10px;
  }

  .filter-container > * {
    margin-left: 0 !important;
  }

  .filter-container ::v-deep .el-date-editor,
  .filter-container ::v-deep .el-input,
  .filter-container ::v-deep .el-select,
  .filter-container ::v-deep .el-button {
    width: 100%;
  }

  .filter-setting-icon {
    align-self: flex-end;
  }

  .table-wrapper {
    margin-top: 10px;
  }

  ::v-deep .el-table {
    min-width: 720px;
    font-size: 12px;
  }

  ::v-deep .el-dialog {
    width: 90% !important;
  }
}
</style>
